package com.xp.flower.qsd.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

public class ServletUtils {

    private ServletUtils() {
    }

    /**
     * 返回指定输入参数，如果不存在，返回空
     *
     * @param request javax.servlet.http.HttpServletRequest
     * @param sKey 指定参数
     * @return 字符
     */
    public static String getRequestValue(HttpServletRequest request, String sKey) {
        if (request.getParameter(sKey) != null) {
            return request.getParameter(sKey);
        } else {
            return "";
        }
    }

    /**
     * 返回指定输入参数名的取值数组，如果取值不存在则返回空。它在参数具有多个取值的情况下十分有用
     *  
     * @param request javax.servlet.http.HttpServletRequest
     * @param sKey 指定参数
     * @return 数组
     */
    public static String[] getRequestValues(HttpServletRequest request, String sKey) {
        if (request.getParameterValues(sKey) != null) {
            return request.getParameterValues(sKey);
        } else {
            return new String[0];
        }
    }

    /**
     * 返回指定Cookie的内容，如果不存在，返回空
     * 
     * @param request javax.servlet.http.HttpServletRequest
     * @param sName Cookie名称
     * @return Cookie内容
     */
    public static String getCookieValue(HttpServletRequest request, String sName) {
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (sName.equalsIgnoreCase(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }

        return "";
    }

    /**
     * 根据指定参数写入Cookie信息
     * 
     * @param request javax.servlet.http.HttpServletRequest
     * @param response javax.servlet.http.HttpServletResponse
     * @param sName Cookie名称
     * @param sValue Cookie内容
     * @param sDomain Cookie域
     * @param iTime Cookie有效期
     */
    public static void setCookieValue(HttpServletRequest request, HttpServletResponse response, String sName, String sValue,
            String sDomain, int iTime) {
        Cookie cookie = new Cookie(sName, sValue);

        cookie.setMaxAge(iTime);
        cookie.setPath("/");

        if (sDomain != null && !"".equals(sDomain)) {
            cookie.setDomain(sDomain);
        }

        response.addCookie(cookie);
    }

    /** 从session里取值 */
    public static Object getSessionValue(HttpServletRequest request, String key) {
        if (request == null || key == null || key.trim().isEmpty())
            return null;

        return request.getSession().getAttribute(key);
    }

    /** 往session里塞值 */
    public static void putSessionValue(HttpServletRequest request, String key, Object value) {
        if (request == null || key == null || key.trim().isEmpty())
            return;

        request.getSession().setAttribute(key, value);
    }

    /** 往页面写入数据 */
    public static void printSuccessJson(Object msg, HttpServletResponse response) {
        printJson("OK", msg, response);
    }

    /** 往页面写入数据 */
    public static void printFailureJson(Object msg, HttpServletResponse response) {
        printJson("ERR", msg, response);
    }

    /** 往页面写入数据 */
    public static void printJson(String code, Object msg, HttpServletResponse response) {
        PrintWriter writer;
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("code", code);
            map.put("msg", msg);

            writer = response.getWriter();
            writer.write(JSON.toJSONString(map));
            writer.flush();
            //                  writer.close();
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }

    /** 往页面写入数据 */
    public static void printText(String text, HttpServletResponse response) {
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
            //                  writer.close();
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }

    /** 上传文件，返回文件名+保存路径 */
    public static String[] uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty())
            return null;

        // 上传文件
        try {
            String fileName = file.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            String imgPath = ConfigUtils.PIC_SHOW_PATH + System.currentTimeMillis() + getRandomNum() + fileName.substring(index);
            File newFile = new File(ConfigUtils.PIC_SAVE_PATH + imgPath);

            file.transferTo(newFile);

            return new String[] { fileName, imgPath };

        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String getRandomNum() {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }

        return sb.toString();
    }

    /** 读取流数据  */
    private static byte[] readStream(InputStream inStream) {
        if (inStream == null)
            return null;

        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;

        try {
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }

            return outSteam.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outSteam != null)
                    outSteam.close();
                if (inStream != null)
                    inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return new byte[] {};
    }

}
